import React from "react";
// import { UploadOutlined } from "@ant-design/icons";
import type { UploadFile, UploadProps } from "antd";
import { Upload } from "antd";
import { useQuery } from "@apollo/client";
import { GET_OSS_INFO } from "@/graphql/oss";
import ImgCrop from "antd-img-crop";
/**
 * OSS图片上传组件
 */

interface OSSDataType {
  dir: string;
  expire: string;
  host: string;
  //   accessId: string;
  policy: string;
  signature: string;
  x_oss_signature_version: string;
  x_oss_credential: string;
  x_oss_date: Date;
  security_token: string;
}

// 这里是上传多个文件
// interface AliyunOSSUploadProps {
//   value?: UploadFile[];
//   onChange?: (fileList: UploadFile[]) => void;
// }
interface AliyunOSSUploadProps {
  maxCount?: number;
  imgCropAspect?: number;
  label?: string;
  value?: UploadFile[];
  onChange?: (files?: UploadFile[]) => void;
  // onChange?: (file?: UploadFile) => void;
}

// // Mock get OSS api
// // https://help.aliyun.com/document_detail/31988.html
// const mockOSSData = () => {
//   const mockData = {
//     dir: 'user-dir/',
//     expire: '1577811661',
//     host: 'https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload',
//     accessId: 'c2hhb2RhaG9uZw==',
//     policy: 'eGl4aWhhaGFrdWt1ZGFkYQ==',
//     signature: 'ZGFob25nc2hhbw==',
//   };
//   return Promise.resolve(mockData);
// };

const OSSImageUpload: React.FC<Readonly<AliyunOSSUploadProps>> = ({
  maxCount = 1,
  imgCropAspect = 1,
  label = "+ 上传图片",
  value = [],
  onChange = () => {},
}) => {
  // const key = useRef<string>("");
  const { data, refetch } = useQuery<{ getOSSInfo: OSSDataType }>(GET_OSS_INFO);
  const OSSData = data?.getOSSInfo;

  // console.log('OSSImageUpload',label,value)
  // console.log('OSSData',OSSData)

  const getKey = (file: UploadFile) => {
    const suffix = file.name.slice(file.name.lastIndexOf("."));
    const key = `${OSSData?.dir}${file.uid}${suffix}`;
    const url = `${OSSData?.host}/${key}`;
    return { key, url };
  };

  //   这是多文件上传
  const handleChange: UploadProps["onChange"] = ({ fileList }) => {
    
    const files = fileList.map((f) => ({
      ...f,
      url: f.url || getKey(f).url,
    }));
    // console.log("Aliyun OSS:", fileList,files);
    onChange?.(files);
  };
  // // 这是单文件上传
  // const handleChange: UploadProps["onChange"] = ({ file }) => {
  //   if (file.status === "removed") {
  //     onChange?.();
  //     return;
  //   }
  //   const newFile = {
  //     ...file,
  //     url: `${OSSData?.host}/${key.current}`,
  //   };
  //   onChange?.(newFile);
  // };

  //   const onRemove = (file: UploadFile) => {
  //     const files = (value || []).filter((v) => v.url !== file.url);
  //     onChange?.(files);
  //   };

  const getExtraData: UploadProps["data"] = (file) => {
    return {
      key: getKey(file).key,
      //   OSSAccessKeyId: OSSData?.accessId,
      policy: OSSData?.policy,
      "x-oss-signature": OSSData?.signature,
      "x-oss-security-token": OSSData?.security_token,
      "x-oss-signature-version": OSSData?.x_oss_signature_version,
      "x-oss-credential": OSSData?.x_oss_credential,
      "x-oss-date": OSSData?.x_oss_date,
      success_action_status: "200",
    };
  };

  const beforeUpload: UploadProps["beforeUpload"] = async (file) => {
    if (!OSSData) {
      return false;
    }

    const expire = Number(OSSData.expire) * 1000;

    if (expire < Date.now()) {
      await refetch();
    }

    return file;
  };

  return (
    <ImgCrop rotationSlider aspect={imgCropAspect}>
      <Upload
        name="file"
        maxCount={maxCount}
        listType="picture-card"
        fileList={value}
        action={OSSData?.host}
        onChange={handleChange}
        data={getExtraData}
        beforeUpload={beforeUpload}
      >
        {/* <Button icon={<UploadOutlined />}>Click to Upload</Button> */}
        {/* + 替换头像 */}
        {label}
      </Upload>
    </ImgCrop>
  );
};
// OSSImageUpload.defaultProps ={
//     value:null,
//     onChange:()=>{},
//     maxCount:1,
// }
export default OSSImageUpload;
